<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>get-xhr</title>
    <script src="/static/js/common.js"></script>
</head>

<body>
    <div>
        <button onclick="getxhr()">请求异步处理</button>
    </div>
    <div>
        <input type="text" id="text_1">
        <button onclick="get_btn_xhr()">发送请求</button>
        <!-- <a id="btn" onclick="get_btn_xhr()">发送请求</a> -->
    </div>
    <div id="showc"></div>
    <script>

        function getxhr() {
            // 1.创建请求
            var xhr = createXhr()

            // 2.创建请求
            xhr.open('get', '/user/get-xhr-server', true) // 参数1是请求类型, 参数2是Django路由, 参数3是否异步或同步(false)

            // 3.设置回调
            xhr.onreadystatechange = function () {

                // 判断xhr的状态(5个状态,0到4)以及服务器的状态(200,404,502)
                if (xhr.readyState == 4 && xhr.status == 200) {
                    // 获取div标签, 通过 xhr.responseText; 拿不到视图函数中的 return HttpResponse("这是一个Ajax请求!")
                    // document.getElementById('show').innerHTML = "这是一个Ajax请求!";
                    document.getElementById('show').innerHTML = xhr.responseText;
                }
            }

            // 4.发送请求
            xhr.send(null) // get模式, 一定为空, post才需要传参

        }

        function get_btn_xhr() {
            var xhr = createXhr()
            // 提前获取标签, 创建异步请求
            var name = document.getElementById('text_1').value;
            // 拼接地址
            var url = '/user/get-xhr-server/?uname=' + name
            xhr.open('get', url, true)
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var show = document.getElementById('showc')
                    //shows.hrdf = url
                    var res = xhr.responseText;
                    show.innerHTML = res;
                    //document.getElementById('showc').innerHTML = xhr.responseText;
                    console.log()
                }
            }
            xhr.send();
        }
    </script>
</body>

</html>